package au.org.nh.xml.generator;

import java.lang.reflect.Field;

public class XMLGeneratorUsingReflection implements XMLGenerator {

	@Override
	public String generate(final Object object)
			throws IllegalArgumentException, IllegalAccessException {
		final Class<?> pojoClass = object.getClass();
		final Field[] fields = pojoClass.getDeclaredFields();

		final StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");
		strBuilder.append("<patientInfo>");

		for (final Field field : fields) {
			field.setAccessible(true);
			if (field.getDeclaringClass().equals(pojoClass)) {
				final Object fieldObj = field.get(object);
				String value = null;
				if (fieldObj instanceof String) {
					value = fieldObj.toString();
					if (isYesNo(value)) {
						value = value.toUpperCase();
					}
				} else {
					continue;
				}

				if (field.getName().equals("maleOrFemale")) {
					value = getMaleFemale(value);
				}

				strBuilder.append("<" + field.getName() + ">" + value + "</"
						+ field.getName() + ">");
			}
		}
		strBuilder.append("</patientInfo>");
		return strBuilder.toString();
	}

	private boolean isYesNo(final String input) {

		if (input == null) {
			return false;
		}

		if (input.equals("Yes") || input.equals("No") || input.equals("Y")
				|| input.equals("N") || input.equals("n") || input.equals("y")) {
			return true;
		}
		return false;
	}

	private String getMaleFemale(final String input) {
		if ("male".equalsIgnoreCase(input)) {
			return "Male";
		} else {
			return "Female";
		}

	}
}
